<?php

namespace app\model;

class PlatformConfigModel extends BaseModel
{
    /**
     * 与模型关联的表名
     *
     * @var string
     */
    protected $table = 'platform_configs';
    
    /**
     * 指示模型主键是否递增
     *
     * @var bool
     */
    public $incrementing = true;

    /**
     * 自动递增ID的"类型"。
     *
     * @var string
     */
    protected $keyType = 'int';

    /**
     * 属性类型转换
     *
     * @var array
     */
    protected $casts = [
        'config_value' => 'array',
        'created_at' => 'timestamp',
        'updated_at' => 'timestamp',
    ];

    /**
     * 根据配置键获取配置
     *
     * @param string $configKey
     * @return array|null
     */
    public static function getConfig(string $configKey): ?array
    {
        $config = self::where('config_key', $configKey)
            ->first();

        return $config ? $config->config_value : null;
    }

    /**
     * 设置配置
     *
     * @param string $configKey
     * @param string $configName
     * @param array $configValue
     * @param string $description
     * @return bool
     */
    public static function setConfig(string $configKey, string $configName, array $configValue, string $description = ''): bool
    {
        return self::updateOrCreate(
            [
                'config_key' => $configKey
            ],
            [
                'config_name' => $configName,
                'config_value' => $configValue,
                'description' => $description
            ]
        ) ? true : false;
    }

    /**
     * 获取所有配置
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function getAllConfigs()
    {
        return self::orderBy('created_at', 'asc')
            ->get();
    }

    /**
     * 删除配置
     *
     * @param string $configKey
     * @return bool
     */
    public static function deleteConfig(string $configKey): bool
    {
        return self::where('config_key', $configKey)
            ->delete() > 0;
    }


}